package jm.demo.gsp;

import groovy.lang.Writable;
import groovy.text.GStringTemplateEngine;
import groovy.text.Template;

import java.io.IOException;

import org.codehaus.groovy.control.CompilationFailedException;
import org.springframework.util.StopWatch;

import com.google.common.collect.ImmutableMap;

public class GStringTemplateDemo {
	
	
	public static void testSimple() {
		GStringTemplateEngine engine = new GStringTemplateEngine();
		try {
			Template template = engine.createTemplate("Dear \"$firstname $lastname\","
					+ "<%" + "\n"
					+ "  out << System.currentTimeMillis()" + "\n"
					+ "%>" + "\n"
					+ "" + "\n"
					+ "" + "\n"
					);
			ImmutableMap<String, String> bind = ImmutableMap.of("firstname", "jiming", "lastname", "liu");
			Writable writer = template.make(bind);
			System.out.println(writer.toString());
			System.out.println(System.currentTimeMillis());
		} catch (CompilationFailedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	

	public static void testSimplePerformance() {
		GStringTemplateEngine engine = new GStringTemplateEngine();
		try {
			Template template = engine.createTemplate("Dear \"$firstname $lastname\","
					+ "<%" + "\n"
					+ "  out << System.currentTimeMillis()" + "\n"
					+ "%>" + "\n"
					+ "" + "\n"
					+ "" + "\n"
					);
			ImmutableMap<String, String> bind = ImmutableMap.of("firstname", "jiming", "lastname", "liu");
			
			StopWatch stopWatch = new StopWatch();
			
			
			long counter = 100;

			stopWatch.start("preheat - " + counter);
			
			for(int i = 0; i < counter; i++) {
				template.make(bind).toString();
			}
			stopWatch.stop();
			
			counter = 200000;
			stopWatch.start("real - " + counter);
			for(int i = 0; i < counter; i++) {
				template.make(bind).toString();
			}
			stopWatch.stop();
			
			System.out.println(stopWatch.prettyPrint());
			

			
		} catch (CompilationFailedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	

	
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		testSimplePerformance();
	}

}
